# app/routers/auth.py
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from datetime import timedelta

from app.schemas.users import Token
from app.crud.users import get_user_by_username
from app.utils.databases import get_db
from app.utils.security import (
    verify_password,
    create_access_token,
    ACCESS_TOKEN_EXPIRE_MINUTES,
)

router = APIRouter()


@router.post("/token", response_model=Token)
async def login_for_access_token(
    form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)
):
    # 验证用户
    user = get_user_by_username(db, username=form_data.username)

    if user:
        # 用户存在
        if verify_password(form_data.password, user.hashed_password):
            # 密码正确: 生成访问令牌
            access_token = create_access_token(data={"sub": user.username})
            return Token(access_token=access_token)
        else:
            # 密码错误
            raise HTTPException(
                status_code=status.HTTP_202_ACCEPTED,
                detail=f"{form_data.username} 密码错误!",
            )
    else:
        # 用户不存在
        raise HTTPException(
            status_code=status.HTTP_202_ACCEPTED,
            detail=f"用户名{form_data.username} 不存在!",
        )
